/// describe
///
/// created by hujintao
/// created at 2021/5/10
//
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterappdriver/pages/home/discover_page.dart';
import 'package:flutterappdriver/pages/mine/mine_page.dart';
import 'package:flutterappdriver/pages/mv/mv_page.dart';
import 'package:flutterappdriver/pages/song_list/song_list.dart';
import 'package:flutterappdriver/utils/network_util.dart';
import 'package:flutterappdriver/widget/floating_player.dart';
import 'package:flutterappdriver/widget/tabs_bottom.dart';
import 'package:flutterappdriver/utils/shared_preference_util.dart';
import 'package:oktoast/oktoast.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;
  List<Widget> pages = [];
  final NetworkUtil networkUtil = NetworkUtil();
  late DateTime lastBackTime;
  bool showFloatPlayer = true;

  final PageController _controller = PageController(
    initialPage: 0,
  );

  void _tapCallback(int index) {
    print("HomePage: on page selected: $index");
    _controller.jumpToPage(index);
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  void initState() {
    super.initState();
    pages
      ..add(SongListPage(tapCallback: this._tapCallback))
      ..add(DiscoverPage())
      ..add(MVPage())
      ..add(MinePage());
    networkUtil.initNetworkListener();
  }

  @override
  void dispose() {
    super.dispose();
    networkUtil.dispose();
    print('HomePage dispose');
  }

  @override
  void deactivate() {
    super.deactivate();
    print('HomePage deactive');
  }

  @override
  Widget build(BuildContext context) {
    print('HomePage build');


    showFloatPlayer =
        SharedPreferenceUtil.getInstance().getBool('showFloatPlayer') ?? true;
    print('showFloatPlayer: $showFloatPlayer');

    return WillPopScope(
        onWillPop: () => _beforePop(context),
        child: Scaffold(
          body: PageView(
            controller: _controller,
            children: pages,
            physics: NeverScrollableScrollPhysics(), // 设置为不能滚动
          ),
          bottomNavigationBar: BottomTabs(
              this._currentIndex, this._tapCallback, showFloatPlayer),
          floatingActionButton: showFloatPlayer ? FloatingPlayer() : null,
          floatingActionButtonLocation:
          FloatingActionButtonLocation.centerDocked,
        ));
  }

  /*Android物理返回键*/
  Future<bool> _beforePop(BuildContext context) async {
    if (this._currentIndex != 0) {
      _tapCallback(0);
      return false;
    }

    if (lastBackTime == null ||
        DateTime.now().difference(lastBackTime) > Duration(seconds: 2)) {
      showToast("再按一次退出");
      lastBackTime = DateTime.now();
      return false; // 不返回
    }

//    Provider.of<MusicController>(context, listen: false).dispose();
    return true;
  }



}
